# Makefile文件，跟于渊老师的略有不同

ENTRYPOINT = 0x30400

ENTRYOFFSET = 0x400

# 汇编编译器
ASM = nasm

DASM = ndisasm

CC = gcc

LD = ld

# 汇编编译选项
ASMBFLAGS = -I boot/include/
ASMKFLAGS = -I include/ -f elf
CFLAGS = -I include/ -m32 -c -fno-builtin
LDFLAGS = -m elf_i386 -s -Ttext $(ENTRYPOINT)
DASMFLAGS = -u -o $(ENTRYPOINT) -e $(ENTRYOFFSET)

BOOT_TARGET = build/boot.bin build/loader.bin
KERNEL_TARGET = build/kernel.bin
OBJS = build/kernel.o build/start.o build/kliba.o build/i8259.o build/protect.o \
	build/klib.o build/string.o build/global.o
DASMOUTPUT = build/kernel.bin.asm

.PHONTY: everything final image clean realclean disasm all buildimg

everything : $(BOOT_TARGET) $(KERNEL_TARGET)

all : realclean everything

final : all clean

image : final buildimg

clean : 
	rm -f $(OBJS)

realclean : 
	rm -f $(BOOT_TARGET) $(KERNEL_TARGET) $(OBJS)
	
disasm:
	$(DASM) $(DASMFLAGS) $(KERNEL_TARGET) > $(DASMOUTPUT)
	
buildimg: createImg build/boot.bin build/loader.bin $(KERNEL_TARGET)
	dd if=build/boot.bin of=build/a.img bs=512 count=1 conv=notrunc
	sudo mount -o loop build/a.img /mnt/floppy
	sudo cp -fv build/loader.bin /mnt/floppy
	sudo cp -fv build/kernel.bin /mnt/floppy
	sudo umount /mnt/floppy
	
createImg:
	dd if=/dev/zero of=build/a.img bs=1474560 count=1	

build/boot.bin: boot/boot.asm boot/include/load_inc.asm boot/include/FAT12Hdr.asm
	$(ASM) $(ASMBFLAGS) -o $@ $<
	
build/loader.bin: boot/loader.asm boot/include/load_inc.asm \
	boot/include/FAT12Hdr.asm boot/include/pm.inc \
	boot/include/lib.inc
	$(ASM) $(ASMBFLAGS) -o $@ $<
	
	
$(KERNEL_TARGET): $(OBJS)
	$(LD) $(LDFLAGS) -o $@ $(OBJS)
	

build/kernel.o: kernel/kernel.asm
	$(ASM) $(ASMKFLAGS) -o $@ $<
	
build/start.o : kernel/start.c include/type.h include/const.h include/protect.h
	$(CC) $(CFLAGS) -o $@ $<
	
build/kliba.o: lib/kliba.asm
	$(ASM) $(ASMKFLAGS) -o $@ $<
	
build/string.o : lib/string.asm
	$(ASM) $(ASMKFLAGS) -o $@ $<

build/i8259.o: kernel/i8259.c
	$(CC) $(CFLAGS) -o $@ $<
	
build/global.o : kernel/global.c
	$(CC) $(CFLAGS) -o $@ $<

build/protect.o : kernel/protect.c
	$(CC) $(CFLAGS) -o $@ $<

build/klib.o : lib/klib.c
	$(CC) $(CFLAGS) -o $@ $<

build/kliba.o : lib/kliba.asm
	$(ASM) $(ASMKFLAGS) -o $@ $<
